import React, { useEffect, useState } from 'react'
import { Menu } from 'antd'
import type { MenuProps } from 'antd'
import styles from './index.module.less'
import { useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom'
import { IMenuItem } from '@/types/menu'
import * as Icons from '@ant-design/icons'
type MenuItem = Required<MenuProps>['items'][number] & { children?: MenuItem[] }

// const items: MenuItem[] = [
//   getItem('工作台', '1', <DesktopOutlined />),

//   getItem('系统管理', 'sub1', <SettingOutlined />, [
//     getItem('用户管理', '5'),
//     getItem('菜单管理', '6'),
//     getItem('角色管理', '7'),
//     getItem('部门管理', '8')
//   ])
// ]

const SideMenu: React.FC<MenuProps> = ({ mode }) => {
  const [menuList, setMenuList] = useState<MenuItem[]>([])
  const [current, setCurrent] = useState('1')
  const [openKeys, setOpenKeys] = useState<string[]>([])

  const routeData: any = useRouteLoaderData('root')
  const navigate = useNavigate()
  const { pathname } = useLocation()

  useEffect(() => {
    const treeMenuList = getMenuList(routeData.menuList)
    setMenuList(treeMenuList)
    setCurrent(pathname)
    initOpenKeys(treeMenuList, pathname)
  }, [])

  const initOpenKeys = (tree: MenuItem[], pathName: string) => {
    const result = searchMenu(tree, pathName)
    setOpenKeys(result.map(item => item?.key) as string[])
  }

  const searchMenu = (tree: MenuItem[], pathName: string, result: MenuItem[] = []): MenuItem[] => {
    for (const item of tree) {
      result.push(item)
      if (item?.key === pathName) return result
      if (item?.children) {
        const res = searchMenu(item?.children, pathName, result)
        if (res) return res
      }
      result.pop()
    }
    return []
  }

  // 创建Icon
  const createIcon = (name?: string) => {
    if (!name) return <></>
    const customIcon: { [key: string]: any } = Icons
    const icon = customIcon[name]
    return React.createElement(icon)
  }

  const getMenuList = (list: IMenuItem[], treeList: MenuItem[] = []) => {
    list.forEach((item, index) => {
      // menu类型是菜单并可用
      if (item.menuType === 1 && item.menuState === 1) {
        // 如果有buttons 说明是最后一层
        if (item.buttons || !item.children)
          return treeList.push(getItem(item.menuName, item.path || index, createIcon(item.icon)))

        treeList.push(
          getItem(item.menuName, item.path || index, createIcon(item.icon), getMenuList(item.children || []))
        )
      }
    })

    return treeList
  }

  const onOpenChange: MenuProps['onOpenChange'] = keys => {
    setOpenKeys(keys)
  }

  function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
    type?: 'group'
  ): MenuItem {
    return {
      key,
      icon,
      children,
      label,
      type
    } as MenuItem
  }
  const onMenuClick: MenuProps['onClick'] = menu => {
    setCurrent(menu.key)
    navigate(menu.key)
  }

  return (
    <div className={styles.sideMenu}>
      <Menu
        openKeys={openKeys}
        onOpenChange={onOpenChange}
        selectedKeys={[current]}
        items={menuList}
        mode={mode}
        onClick={onMenuClick}
        className={styles.menu}
      />
    </div>
  )
}

export default SideMenu
